"use strict"

const BaseController = require("./base")

const utility = require("utility")
const WXBizDataCrypt = require("../middleware/WXBizDataCrypt")
class WxUserController extends BaseController {
  //获取所有微信用户信息
  async index() {
    const { ctx, service } = this
    const { pageNum, pageSize, ...where } = ctx.query
    const result = await service.wxuser.list(
      isNaN(pageNum) ? 1 : parseInt(pageNum),
      isNaN(pageSize) ? 3 : parseInt(pageSize),
      where
    )
    if (result) {
      this.Success(result, "获取成功")
    } else {
      this.Error("获取失败")
    }
  }

  //获取单条微信用户信息
  async single() {
    const { ctx, service } = this
    const id = ctx.params.id
    const result = await service.wxuser.single(id)
    if (result) {
      this.Success(result, "获取成功")
    } else {
      this.Error("获取失败")
    }
  }
  //获取用户的喜欢 关注 粉丝
  async getUserLike() {
    const { ctx, service } = this
    const id = ctx.params.id
    const result = await service.wxuser.openIdSingle(id)
    if (result) {
      this.Success(result, "获取成功")
    } else {
      this.Error("获取失败")
    }
  }
  //获取小程序openid
  async wxOpenId() {
    const { ctx, app, service } = this
    const appid = app.config.wxApp.book.appid
    const secret = app.config.wxApp.book.secret
    const { code } = ctx.request.body
    let res = await ctx.curl(
      "https://api.weixin.qq.com/sns/jscode2session?appid=" +
        appid +
        "&secret=" +
        secret +
        "&js_code=" +
        code +
        "&grant_type=authorization_code"
    )
    const result = JSON.parse(res.data.toString());
    console.log(result);
    if (result) {
      let data = {
        sessionkey: result.session_key,
      }
      this.Success({data, msg: "获取成功"})
    }else{
      this.Error({msg:"获取失败"});
    }
  }
  //处理小程序用户登录
  async wxLogin() {
    const { ctx, app, service } = this
    let appId = app.config.wxApp.book.appid
    const { sessionKey, encryptedData, iv } = ctx.request.body
    const pc = new WXBizDataCrypt(appId, sessionKey)
    const userInfo = pc.decryptData(encryptedData, iv)
    if (userInfo) {
      this.Success(userInfo, "登录成功")
    } else {
      this.Error("登录失败")
    }
  }
}
module.exports = WxUserController
